package com.erpanderp.wam.asset.view;

import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;
import java.util.TreeMap;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.swing.SwingWorker;

import com.erpanderp.wam.asset.model.entity.AssetDetails;
import com.erpanderp.wam.asset.model.entity.AssetRequest;
import com.erpanderp.wam.asset.model.service.AssetRequestDAO;
import com.erpanderp.wam.usm.model.entity.user.Employee;
import com.erpanderp.wam.usm.model.entity.user.WAMUser;
import com.erpanderp.wam.usm.model.service.user.EmployeeDAO;
import com.erpanderp.wam.util.CommonLookup;
import com.erpanderp.wam.util.EmailUtil;
import com.erpanderp.wam.util.ValidationUtil;
import com.erpanderp.wam.util.WAMHostManager;

@ManagedBean
@ViewScoped
public class ApproveAssetRequestBean implements Serializable{
 
	 
	private static final long serialVersionUID = 1L;
	private HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
	ServletContext context = (ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext();
	HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(true);
	private WAMUser wamUser = (WAMUser) session.getAttribute(CommonLookup.SESSION_ATTRIBUTE_WAMUSER);
	private TimeZone timeZone = TimeZone.getDefault();
	
	private String activity;
	private String assetCode;
	private boolean FORM_VALID;
	private EmailUtil emailUtil;
	private String EMAIL_MESSAGE;
	private String rejectId; 
	private Long selectedSysAdmin;
	private boolean renderBackButton; 
	
	private AssetRequest assetRequest=new AssetRequest();
	private Employee assigedByEmployee = new Employee();
	
	private AssetRequestDAO assetRequestDAO =new AssetRequestDAO();
	private EmployeeDAO employeeDAO=new EmployeeDAO();
	
	private List<AssetDetails> assetDetailsList = new ArrayList<AssetDetails>(); 
	//private List<AssetDetails> updateAssetDetailsList = new ArrayList<AssetDetails>(); 
	private Map<String, Long> systemAdminsMap = new TreeMap<String, Long>();
	private List<Employee> systemAdminstrators = new ArrayList<Employee>();
	
	
	public ApproveAssetRequestBean() {
		assetCode=request.getParameter("assetCode");
		activity=request.getParameter("activity");
		
	    assetRequest = assetRequestDAO.getAssetRequestByAssetCode(assetCode);
	    if(assetRequest.getAssigedByEmployee() != null){
	    	//assetRequest.setAssigedByEmployee(assigedByEmployee);
	    	selectedSysAdmin = assetRequest.getAssigedByEmployee().getEmployeeId();
	    	
	    }
	    assetDetailsList.clear();
	    assetDetailsList.addAll(assetRequest.getAssetDetails());
	    
	    systemAdminstrators=employeeDAO.getEmployeeByModuleName("System Administration");
		for (Employee systenAdmin : systemAdminstrators) {
			systemAdminsMap.put(systenAdmin.getFirstName()+" "+systenAdmin.getLastName(), systenAdmin.getEmployeeId());
		}
		
		if(wamUser != null){
			setRenderBackButton(true);
		}else{	
			setRenderBackButton(false);
		}
		
	}
	
	// Recommend Action
		public void recommenderRecommendListener(ActionEvent e) {
			validateForm();
			if (FORM_VALID) {
				Employee sysAdmin = employeeDAO.getEmployeeByEmployeeId(selectedSysAdmin);
												
				for(AssetDetails as : assetDetailsList){
					as.setAssetAssignedBy(sysAdmin);					
				}
				assetRequest.setRecommenderStatus(CommonLookup.STATUS_RECOMMENDED);	
				
				assetRequest.setAssigedByEmployee(sysAdmin);
				assetRequestDAO.saveOrUpdateAssetRequest(assetRequest);
				FacesContext.getCurrentInstance().addMessage(null,new FacesMessage(FacesMessage.SEVERITY_INFO,
								"You have recommended successfully.", ""));

				// MAIL TRIGGERING CODE
				System.out.println("AT CALLER METHOD: " + sendMessage()); // *******DONT REMOVE*******
			}
		}
		public void rejectListener(ActionEvent e) {
			validateForm();
			if (FORM_VALID) {
				assetRequest.setRecommenderStatus(CommonLookup.STATUS_REJECTED);
				Employee sysAdmin = employeeDAO.getEmployeeByEmployeeId(selectedSysAdmin);
				System.out.println("=============sysAdmin================"+sysAdmin);
				assetRequest.setAssigedByEmployee(sysAdmin);
				assetRequestDAO.saveOrUpdateAssetRequest(assetRequest);
				FacesContext.getCurrentInstance().addMessage(null,new FacesMessage(FacesMessage.SEVERITY_INFO," You have rejected aseet request.", ""));
				
				rejectId = e.getComponent().getId().toString();
				
				// MAIL TRIGGERING CODE
				System.out.println("AT CALLER METHOD: " + rejectMessage()); // *******DONT REMOVE*******
			}
		}
		
		public void approveListener(ActionEvent e) {
			approverValidateForm();
			if (FORM_VALID) {
				Employee sysAdmin = employeeDAO.getEmployeeByEmployeeId(selectedSysAdmin);
			
				for(AssetDetails as : assetDetailsList){
					as.setAssetAssignedBy(sysAdmin);					
				}
				assetRequest.setApproverStatus(CommonLookup.STATUS_APPROVED);				
				
				assetRequest.setAssigedByEmployee(sysAdmin);
				assetRequestDAO.saveOrUpdateAssetRequest(assetRequest);
				FacesContext.getCurrentInstance().addMessage(null,new FacesMessage(FacesMessage.SEVERITY_INFO," You have approved successfully.", ""));

				// MAIL TRIGGERING CODE
				System.out.println("AT CALLER METHOD: " + approverMail()); // *******DONT REMOVE*******
			}
		}
		private void approverValidateForm() {
			FORM_VALID=true;
			if (ValidationUtil.isEmpty(assetRequest.getApproverComments(),
					"Your Comments", null, FacesContext.getCurrentInstance()) != null) {
				FORM_VALID = false;
			}

		}
	//RECOMMEND MAIL
		public String sendMessage() {
			Map<String, String> hostsMap = WAMHostManager.getWAMHosts(context);
			String domainName = context.getInitParameter("domainName");
			String messageString = "";
			
			SimpleDateFormat formate = new SimpleDateFormat("dd-MMM-yyyy");
			String requestDate = formate.format(assetRequest.getRequestDate());
			
			emailUtil = new EmailUtil();
			if (hostsMap.get(CommonLookup.DEV_EMAIL) == null) {
				String[] to = { assetRequest.getApprovedBy().getEmail() };
				emailUtil.setRecieverAddresses(to);			
			} else {
				String[] to = { hostsMap.get(CommonLookup.DEV_EMAIL) };
				emailUtil.setRecieverAddresses(to);			
			}

			String requestURL = "asset/approveassetrequest.html?assetCode=" + assetCode+ "&activity=byApprover";
			String privateLink = "http://" + hostsMap.get(CommonLookup.PRIVATEHOST)
					+ "/" + domainName + "/" + requestURL;
			String publicLink = "http://" + hostsMap.get(CommonLookup.PUBLICHOST)
					+ "/" + domainName + "/" + requestURL;

			messageString = "Dear " + assetRequest.getApprovedBy().getFirstName()
					+ " " + assetRequest.getApprovedBy().getLastName() + ""
					+ ",<br /><br />" +
					"<b>New asset request raised by </b>" +
					"<table style='border: 1px solid #d9d9d9;'>"
					+ "<tr> <td>Employee Name</td><td> : </td><td>"
					+ assetRequest.getEmployee().getFirstName() + " "
					+ assetRequest.getEmployee().getLastName() + "</td></tr>"
					+ "<tr> <td>Employee Code</td><td> : </td><td>"
					+ assetRequest.getEmployee().getEmployeeCode() + " </td></tr>"
					+ "<tr> <td>Asset Request Code</td><td> : </td><td>"
					+ assetRequest.getAssetReferenceCode()+ " </td></tr>"
					+ "<tr> <td>Request Date </td><td> : </td><td>"
					+ requestDate + " </td></tr>"
					+ "</table><br/>"
					+ "<a style='color:#FF9933;font-weight: bold;' href=\""
					+ privateLink + "\">"
					+ "Please click here to Approve/Reject asset request"
					+ "</a /><br />" + "(Employees who are in Hyderabad office)"
					+ "<br /><br />"
					+ "<a style='color:#FF9933;font-weight: bold;' href=\""
					+ publicLink + "\">"
					+ "Please click here to Approve/Reject asset request"
					+ "</a /><br />" + "(out side Hyderabad office)"
					+ "<br /><br />" +

					"Thanks & Regards, <br />" + CommonLookup.WAM_DEVTEAM_SIGNATURE;
			emailUtil.setMessage(messageString);
			emailUtil.setSenderEmail("podquick@erpanderp.com", "WAM - Dev Team");
			emailUtil.setSubject("Approve "
					+ assetRequest.getEmployee().getFirstName() + " "
					+ assetRequest.getEmployee().getLastName() + "( "
					+ assetRequest.getAssetReferenceCode() + " ) - Asset Request");

			SwingWorker worker = new SwingWorker<String, Object>() {
				@Override
				protected String doInBackground() throws Exception {
					EMAIL_MESSAGE = emailUtil.processAndSendEmail();
					return null;
				}

				@Override
				protected void done() {
					System.out.println("DONE " + EMAIL_MESSAGE);
				}
			};
			worker.execute();
			System.out.println("BEFORE RETURNING: " + EMAIL_MESSAGE);
			return EMAIL_MESSAGE;
		}
		
		// REJECT MAIL
		public String rejectMessage() {
			String messageString = "";

			String employeeMail = "sravani.m@erpanderp.com";
			Map<String, String> hostsMap = WAMHostManager.getWAMHosts(context);
			emailUtil = new EmailUtil();
			if (hostsMap.get(CommonLookup.DEV_EMAIL) == null) {
				String[] to = { assetRequest.getApprovedBy().getEmail() };
				emailUtil.setRecieverAddresses(to);			
			} else {
				String[] to = { hostsMap.get(CommonLookup.DEV_EMAIL) };
				emailUtil.setRecieverAddresses(to);			
			}
			
			String comments=""; 
			if(rejectId.equalsIgnoreCase("recommender")){
				comments = assetRequest.getRecommenderComments();
			}
			if(rejectId.equalsIgnoreCase("approver")){
				comments = assetRequest.getApproverComments();
			}

			messageString = "Dear " + assetRequest.getEmployee().getFirstName()
					+ " " + assetRequest.getEmployee().getLastName() + ""
					+ ",<br /><br />" +

					"Your asset request form " + "<b>( "
					+ assetRequest.getAssetReferenceCode() + " )</b>"
					+ " Need Some Modifications.Please Re-submit once.<br><br>"
					+ "<b>Approval Comments : </b> "	+ comments + "<br><br>" +

					"Thanks & Regards, <br />" + CommonLookup.WAM_DEVTEAM_SIGNATURE;
			
			emailUtil.setMessage(messageString);
			emailUtil.setSenderEmail("podquick@erpanderp.com", "WAM - Dev Team");
			emailUtil.setSubject(
					 assetRequest.getEmployee().getFirstName() + " "
					+ assetRequest.getEmployee().getLastName() + "( "
					+ assetRequest.getAssetReferenceCode()
					+ " ) - Re-Submit again asset request form ");

			SwingWorker worker = new SwingWorker<String, Object>() {
				@Override
				protected String doInBackground() throws Exception {
					EMAIL_MESSAGE = emailUtil.processAndSendEmail();
					return null;
				}

				@Override
				protected void done() {
					System.out.println("DONE " + EMAIL_MESSAGE);
				}
			};
			worker.execute();
			System.out.println("BEFORE RETURNING: " + EMAIL_MESSAGE);
			return EMAIL_MESSAGE;
		}
		
		public String approverMail() {
			Map<String, String> hostsMap = WAMHostManager.getWAMHosts(context);
			String domainName = context.getInitParameter("domainName");
			String messageString = "";

			emailUtil = new EmailUtil();
			if (hostsMap.get(CommonLookup.DEV_EMAIL) == null) {
				String[] to = { assetRequest.getAssigedByEmployee().getEmail() };
				emailUtil.setRecieverAddresses(to);			
			} else {
				String[] to = { hostsMap.get(CommonLookup.DEV_EMAIL) };
				emailUtil.setRecieverAddresses(to);
				//emailUtil.setCCAddresses(to);						
			}
		String requestURL = "asset/assignassets.html?assetCode=" + assetCode;
		String privateLink = "http://" + hostsMap.get(CommonLookup.PRIVATEHOST)
				+ "/" + domainName + "/" + requestURL;
		String publicLink = "http://" + hostsMap.get(CommonLookup.PUBLICHOST)
					+ "/" + domainName + "/" + requestURL;

		messageString = "Dear " + assetRequest.getAssigedByEmployee().getFirstName()
					+ " " + assetRequest.getAssigedByEmployee().getLastName() + ""
					+ ",<br />"+
					"<p>Please assign asset(s) to the following employee</p>" +
					"<table style='border: 1px solid #d9d9d9;'>" +
			        "<tr> <td>Employee Name</td><td> : </td><td>" + assetRequest.getEmployee().getFirstName()+" "+assetRequest.getEmployee().getLastName()+"</td></tr>" +
			        "<tr> <td>Employee Code</td><td> : </td><td>" + assetRequest.getEmployee().getEmployeeCode()+"</td></tr>" +
			        "<tr> <td>Request Date</td><td> : </td><td>" + assetRequest.getRequestDate()+ " </td></tr>" +
			        "<tr> <td>Asset Request Code</td><td> : </td><td>" + assetRequest.getAssetReferenceCode()+ " </td></tr>" +					        						       
			        "</table><br/>"+	
					"<a style='color:#FF9933;font-weight: bold;' href=\""
					+ privateLink + "\">"
					+ "Please click here to allot/assign asset(s) to above employee"
					+ "</a /><br />" + "(Employees who are in Hyderabad office)"
					+ "<br /><br />"
					+ "<a style='color:#FF9933;font-weight: bold;' href=\""
					+ publicLink + "\">"
					+ "Please click here to allot/assign asset(s) to above employee"
					+ "</a /><br />" + "(out side Hyderabad office)"
					+ "<br /><br />" +

					"Thanks & Regards, <br />" + CommonLookup.WAM_DEVTEAM_SIGNATURE;
			
			emailUtil.setMessage(messageString);
			emailUtil.setSenderEmail("podquick@erpanderp.com", "WAM - Dev Team");

			emailUtil.setSubject( assetRequest.getEmployee().getFirstName() + " "
							+ assetRequest.getEmployee().getLastName() + "( "
							+ assetRequest.getAssetReferenceCode()
							+ " ) - Asset Request is Approved");

			SwingWorker worker = new SwingWorker<String, Object>() {
				@Override
				protected String doInBackground() throws Exception {
					EMAIL_MESSAGE = emailUtil.processAndSendEmail();
					return null;
				}

				@Override
				protected void done() {
					System.out.println("DONE " + EMAIL_MESSAGE);
				}
			};
			worker.execute();
			System.out.println("BEFORE RETURNING: " + EMAIL_MESSAGE);
			return EMAIL_MESSAGE;
		}
		
		// Validations Test
		private void validateForm() {
			FORM_VALID=true;
			if (ValidationUtil.isEmpty(assetRequest.getRecommenderComments(),
					"Your Comments", null, FacesContext.getCurrentInstance()) != null) {
				FORM_VALID = false;
			}
		}


	
	//SETTERS AND GETTERS
	public String getActivity() {
		return activity;
	}

	public void setActivity(String activity) {
		this.activity = activity;
	}

	public String getAssetCode() {
		return assetCode;
	}


	public void setAssetCode(String assetCode) {
		this.assetCode = assetCode;
	}


	public AssetRequest getAssetRequest() {
		return assetRequest;
	}


	public void setAssetRequest(AssetRequest assetRequest) {
		this.assetRequest = assetRequest;
	}


	public AssetRequestDAO getAssetRequestDAO() {
		return assetRequestDAO;
	}


	public void setAssetRequestDAO(AssetRequestDAO assetRequestDAO) {
		this.assetRequestDAO = assetRequestDAO;
	}


	public List<AssetDetails> getAssetDetailsList() {
		return assetDetailsList;
	}


	public void setAssetDetailsList(List<AssetDetails> assetDetailsList) {
		this.assetDetailsList = assetDetailsList;
	}

	public String getRejectId() {
		return rejectId;
	}

	public void setRejectId(String rejectId) {
		this.rejectId = rejectId;
	}

	public TimeZone getTimeZone() {
		return timeZone;
	}

	public void setTimeZone(TimeZone timeZone) {
		this.timeZone = timeZone;
	}
	
	public Map<String, Long> getSystemAdminsMap() {
		return systemAdminsMap;
	}

	public void setSystemAdminsMap(Map<String, Long> systemAdminsMap) {
		this.systemAdminsMap = systemAdminsMap;
	}

	public EmployeeDAO getEmployeeDAO() {
		return employeeDAO;
	}

	public void setEmployeeDAO(EmployeeDAO employeeDAO) {
		this.employeeDAO = employeeDAO;
	}

	public List<Employee> getSystemAdminstrators() {
		return systemAdminstrators;
	}

	public void setSystemAdminstrators(List<Employee> systemAdminstrators) {
		this.systemAdminstrators = systemAdminstrators;
	}

	public Employee getAssigedByEmployee() {
		return assigedByEmployee;
	}

	public void setAssigedByEmployee(Employee assigedByEmployee) {
		this.assigedByEmployee = assigedByEmployee;
	}

	public Long getSelectedSysAdmin() {
		return selectedSysAdmin;
	}

	public void setSelectedSysAdmin(Long selectedSysAdmin) {
		this.selectedSysAdmin = selectedSysAdmin;
	}

	public boolean isRenderBackButton() {
		return renderBackButton;
	}

	public void setRenderBackButton(boolean renderBackButton) {
		this.renderBackButton = renderBackButton;
	}

	public WAMUser getWamUser() {
		return wamUser;
	}

	public void setWamUser(WAMUser wamUser) {
		this.wamUser = wamUser;
	}
	
}
